package day15.socketdemo07;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Xiao
 * @date 2021/8/9
 */
public class ServerDemo07 {
    /**
     * 需求：
     * 客户端：将本地文件上传到服务器，接收服务器的反馈；
     * 服务器：接收客户端上传的文件，上传完毕之后给出反馈。
     */
    public static void main(String[] args) throws IOException {
        //创建服务器ServerSocket对象，指定端口
        ServerSocket ss = new ServerSocket(10000);
        //创建Socket对象监听客户端连接
        Socket so = ss.accept();
        BufferedWriter bw = getBufferedWriter(so);
//        BufferedOutputStream bos = getBufferedOutputStream(so);
        //创建服务器输出流对象
        BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
        //反馈信息给客户端
        bw1.write("已经完成上传工作，Over！");
        bw1.newLine();
        bw1.flush();

        //关闭本地IO流和服务器IO流
        bw.close();
//        bos.close();
        so.close();
        ss.close();
    }

    /**字节流接收数据*/
    private static BufferedOutputStream getBufferedOutputStream(Socket so) throws IOException {
        //创建服务器输入流对象
        BufferedInputStream bis = new BufferedInputStream(so.getInputStream());
        //创建本地输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(
                "videoPractice\\src\\day15\\socketdemo07\\demo07Copy.txt"));
        //通过服务器输入流对象读入TCP通信传输的文件，通过本地输出流写出文件
        int i;
        while ((i = bis.read()) != -1) {
            System.out.println(i);
            bos.write(i);
        }
        bos.flush();
        return bos;
    }

    /**字符流接收数据*/
    private static BufferedWriter getBufferedWriter(Socket so) throws IOException {
        //创建服务器输入流对象
        BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream()));
        //创建本地输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter(
                "videoPractice\\src\\day15\\socketdemo07\\demo07Copy.txt"));
        //通过服务器输入流对象读入TCP通信传输的文件，通过本地输出流写出文件
        String s;
        while ((s = br.readLine()) != null) {
            System.out.println(s);
            bw.write(s);
            bw.newLine();
        }
        bw.flush();
        //标记结束服务器输入完毕
        return bw;
    }
}
